<template>
  <div class="page_content">
    <header>
      <van-nav-bar class="main_header" title="所属机构/团体">
        <template #left>
          <span @click="goBack">返回</span>
        </template>
        <template #right>
          <van-icon name="add-o" color="#000" size="18px" @click="openDelegationDialog" />
        </template>
      </van-nav-bar>
    </header>
    <div class="main_content">
      <van-empty v-if="!delegationInfo.length" description="暂未加入机构，快去选择一个机构加入吧" />
      <div v-else class="delegation_content">
        <div v-for="(item, index) in delegationInfo" :key="index" class="delegation_item">
          <van-row class="gl_px_10 gl_py_10">
            <van-col :span="8" align="left">
              <van-image
                round
                width="80px"
                height="80px"
                :src="getStaticFileUrl(item.imagePath)"
              />
            </van-col>
            <van-col :span="16">
              <div class="name gl_my_5">{{ item.name }}</div>
              <div class="area gl_my_5">地区：{{ addressDataForCheck(item) }}</div>
              <div class="area gl_my_5">类型：{{ item.delegationType && item.delegationType.name }}</div>
            </van-col>
          </van-row>
          <van-button type="default" size="small" plain :loading="exitBtnLoading" :hairline="true" block @click="handleSubmitDeleteOrgan(item.id)">
            退出
          </van-button>
        </div>
      </div>
    </div>
    <!-- 加入团体列表 -->
    <van-popup
      v-model="delegationDialog"
      get-container="#app"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <div class="delegation_popup">
        <div v-if="delegationLoading" class="page_loading">
          <van-loading size="24px" vertical color="#fff">加载中...</van-loading>
        </div>
        <div class="delegation_popup_title">
          <van-nav-bar title="加入机构">
            <template #left>
              <span @click="delegationDialog = false">返回</span>
            </template>
          </van-nav-bar>
          <div class="search_input">
            <input v-model="delegationQO.Filter" type="text" placeholder="请输入机构名称" @blur="searchDelegation">
            <div class="search_icon" @click="searchDelegation">
              <van-icon name="search" size="22px" color="#1890ff" style="vertical-align: middle;" />
            </div>
          </div>
        </div>
        <div class="delegation_popup_content">
          <div v-if="delegationList.length" class="delegation_list">
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
              <van-list
                v-model="loading"
                :finished="finished"
                finished-text=""
                error-text="请求失败，点击重新加载"
                :error.sync="error"
                @load="getOrganData"
              >
                <div v-for="item in delegationList" :key="item.id" class="delegation_item">
                  <van-row class="gl_px_10 gl_py_10">
                    <van-col :span="8" align="left">
                      <van-image
                        round
                        width="80px"
                        height="80px"
                        :src="getStaticFileUrl(item.imagePath)"
                      />
                    </van-col>
                    <van-col :span="16">
                      <div class="name gl_my_5">{{ item.name }}</div>
                      <div class="area gl_my_5">{{ item.teamName }}</div>
                      <div class="area gl_my_5">地址：{{ addressDataForCheck(item) }}</div>
                      <div class="area gl_my_5">联系方式：{{ item.phoneNumber }}</div>
                    </van-col>
                  </van-row>
                  <van-button type="primary" size="small" :loading="exitBtnLoading" :hairline="true" block @click="handleSubmitAddOrgan(item.id)">申请加入</van-button>
                </div>
              </van-list>
            </van-pull-refresh>
          </div>
          <van-empty v-else description="暂无机构数据" />
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { Api_GET_EventsManagementDelegationQO } from '@/lib/form/game/swaggerForm';
import {
  api_POST_EventsManagementRegisterQuitDelegationDelegationId,
  api_GET_EventsManagementDelegation,
  api_POST_EventsManagementRegisterJoinDelegationDelegationId
} from '@/extend/api/gameswaggerApi/app';
export default {
  data() {
    return {
      exitBtnLoading: false,
      delegationLoading: false,
      delegationInfo: [],
      delegationDialog: false,
      delegationQO: new Api_GET_EventsManagementDelegationQO(),
      delegationList: [],
      total: 0,
      // 是否处于加载状态
      loading: false,
      // 是否已经加载完成
      finished: false,
      // 是否加载失败
      error: false,
      refreshing: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache,
      currentUserType: state => state.user.currentUserType
    })
  },
  watch: {
    currentUserType: {
      handler(val) {
        if (!val) return;
        this.getCurrentDelegationInfo();
      }
    }
  },
  created() {
    this.getDict();
    this.getDictByType(['district']);
    if (this.currentUserType) {
      this.getCurrentDelegationInfo();
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    // 获取当前所属机构信息
    getCurrentDelegationInfo() {
      const _qo = {
        RegisterId: this.currentUserType.registerId,
        IncludeDelegation: true,
        IncludeDelegationType: true
      };
      api_GET_EventsManagementDelegation(_qo).then(res => {
        this.delegationInfo = res.items || [];
        console.log(res);
      }, error => {
        this.$toast.fail(`获取当前所属机构信息失败！${error.error.message}`);
      });
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    // 退出团体
    handleSubmitDeleteOrgan(id) {
      this.$dialog.confirm({
        title: '提示',
        message: '您确定要退出当前机构吗？'
      }).then(() => {
        this.exitBtnLoading = true;
        api_POST_EventsManagementRegisterQuitDelegationDelegationId(id).then(() => {
          this.exitBtnLoading = false;
          this.getCurrentDelegationInfo();
        }, error => {
          this.exitBtnLoading = false;
          this.$toast.fail(error.error.message);
        });
      });
    },
    openDelegationDialog() {
      this.delegationQO = new Api_GET_EventsManagementDelegationQO();
      this.delegationList = [];
      this.getOrganData();
      this.delegationDialog = true;
    },
    // 获取可加入列表
    getOrganData() {
      this.finished = false;
      if (this.refreshing) {
        this.delegationList = [];
        this.refreshing = false;
        this.delegationQO.Page = 1;
      }
      this.delegationQO.SkipCount = (this.delegationQO.Page - 1) * this.delegationQO.MaxResultCount;
      this.delegationQO.IsApproved = null;
      this.delegationQO.IsBelong = false;
      this.delegationQO.RegisterId = this.currentUserType.registerId;
      api_GET_EventsManagementDelegation(this.delegationQO).then(res => {
        this.total = res.totalCount;
        this.delegationList = this.delegationList.concat(res.items);
        this.loading = false;
        if (this.total > this.delegationList.length) {
          this.delegationQO.Page += 1;
        } else {
          this.finished = true;
        }
      }, error => {
        this.loading = false;
        this.$toast.fail(error.error.message);
      });
    },
    searchDelegation() {
      this.refreshing = true;
      this.delegationList = [];
      this.onRefresh();
    },
    onRefresh() {
      this.finished = false;
      if (this.loading) return;
      this.loading = true;
      this.getOrganData();
    },
    // 申请加入团体
    handleSubmitAddOrgan(id) {
      this.delegationLoading = true;
      api_POST_EventsManagementRegisterJoinDelegationDelegationId(id).then(res => {
        this.getCurrentDelegationInfo();
        this.delegationDialog = false;
        this.delegationLoading = false;
        this.$toast.success('操作成功');
      }, error => {
        this.$toast.fail(error.error.message);
        this.delegationLoading = false;
      });
    },
    // 处理地址显示
    handleArea(delegation) {
      return (delegation.provinceCode || '') + (delegation.cityCode || '') + (delegation.countyCode || '');
    },
    addressDataForCheck (data) {
      const _provinceCode = data.provinceCode;
      const _cityCode = data.cityCode;
      const _countyCode = data.countyCode;
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      return `${_provinceData ? _provinceData.name : ''} ${_cityData ? _cityData.name : ''} ${_countyData ? _countyData.name : ''}`;
    },
    goBack() {
      this.$router.push({
        path: `/myCenter${this.$route.params.id && '/' + this.$route.params.id || ''}/individual`
      });
    }
  }
};
</script>
<style>
.delegation_item {
  margin: 5px 10px 10px;
  border-radius: 5px;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.09);
}
.delegation_item .name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.delegation_item .area {
  color: #848484;
  font-size: 12px;
}
.delegation_popup .delegation_popup_title {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 96px;
}
.delegation_popup  .delegation_popup_content {
  position: absolute;
  top: 96px;
  bottom: 0;
  left: 0;
  width: 100%;
  overflow: auto;
}
.delegation_list {
  min-height: 100%;
}
.delegation_list .van-pull-refresh {
  min-height: calc(100vh - 100px);
}
.delegation_list .van-pull-refresh__track {
  min-height: calc(100vh - 100px);
}
.search_input {
  position: relative;
  width: 100%;
  padding: 5px 10px;
}
.search_input input {
  width: 100%;
  height: 40px;
  padding: 2px 40px 2px 20px;
  border: 1px solid #eee;
  border-radius: 5px;
  font-size: 14px;
  outline: none;
  transition: all 0.3s ease;
}
.search_input .search_icon {
  position: absolute;
  right: 10px;
  top: 5px;
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
}
.search_input input:focus {
  border: 1px solid #1890ff;
}
</style>
